########################################
## ECONOMIC SHOCKS & ISSUE IMPORTANCE ##
## Author:  Sarah Gomm                ##
## Date:    February 2023             ##
## Data:    SEP Wave 6                ##
########################################


##############################
# STANDARD CONJOINT ANALYSIS 
##############################

# Check the username and set the working directory   ---------------------------
# Get the username 
username <- Sys.getenv("USERNAME")


if (username == "FILL IN YOUR USERNAME") {
  setwd("FILL IN YOUR WORKING DIRECTORY")
} else {
  stop("Unknown user. Please check your username.")
}



#Install & load packages   -----------------------------------------------------
packages <- c("here", "tidyverse", "haven", "labelled", "cregg", "data.table") 

for (p in packages) {
  if (p %in% installed.packages()[,1]) require(p, character.only=T)
  else {
    install.packages(p)
    library(p, character.only=T)
  }
  if (p %in% rownames(.packages()) == FALSE)
  {library(p, character.only=T)
  }
}

#Load data     -----------------------------------------------------------------
load(dfconj, file = "w6_conjoint.RData")


# DATA ANALYSIS -----------------------------------------------------------

# Plot marginal means and AMCEs -------------------------------------------

f1 <- choice ~ Env1 + Env2 + Env3 + Env4 + Eco1 + Eco2 + Eco3 + Eco4 + EcoEnv1 + EcoEnv2 + EcoEnv3 + EcoEnv4 + Oth1 + Oth2 + Oth3 + Oth4

mm <- mm(dfconj, f1, id = ~ PubId, h0 = 0.5, level_order = "descending")

p1 <- (plot(mm, feature_headers = FALSE, 
            vline = 0.5, 
            xlab = "Marginal Means (Scale 0-1)", 
            ylab = "Attribute levels",
            legend_title = "Policy positions"))


p1 + ggplot2::facet_wrap(~feature, ncol = 1L, 
                         scales = "free_y", strip.position = "left") +
  ggtitle("Candidate preferences - Conjoint (Marginal Means)")


# Plots to compare effect sizes between respondents

tiff("Appendix_MarginalMeans_Conjoint.tiff", units="in", width=12, height=11, res=500)
mm_stacked <- cj(dfconj, choice ~ Env1 + Env2 + Env3 + Env4 + 
                   Eco1 + Eco2 + Eco3 + Eco4 + EcoEnv1 + EcoEnv2 + EcoEnv3 + 
                   EcoEnv4 + Oth1 + Oth2 + Oth3 + Oth4, 
                 id = ~ PubId,
                 estimate = "mm", by = ~ Affectedness)

p3a <- plot(mm_stacked, group = "Affectedness", feature_headers = T,
           vline = 0.5,
           xlab = "Marginal means (Scale 0-1)",
           ylab = "Attribute levels ")

p3a + ggtitle("Candidate preferences - Conjoint (Marginal Means)")
p3a + ggplot2::facet_wrap(~feature, ncol = 1L, 
                         scales = "free_y", strip.position = "left") +
  ggtitle("Candidate preferences - Conjoint (Marginal Means)")

dev.off()

